// ==UserScript==
// @name         HACG磁力链接修复
// @namespace    https://www.hacg.icu/
// @version      1.2
// @description  给【琉璃神社】文章中的磁力链接添加磁力链接头
// @author       DeepSeek
// @match        *://*.hacg.*/*
// @grant        none
// @icon         https://www.hacg.icu/favicon.ico
// @updateURL    https://gitee.com/selling-surprises/Greasyfork-Script-repository/raw/main/%E5%AE%9E%E7%94%A8%E8%84%9A%E6%9C%AC/HACG%E7%A3%81%E5%8A%9B%E9%93%BE%E6%8E%A5%E4%BF%AE%E5%A4%8D/HACG%E7%A3%81%E5%8A%9B%E9%93%BE%E6%8E%A5%E4%BF%AE%E5%A4%8D.user.js
// @run-at       document-end
// ==/UserScript==

(function() {
    'use strict';

    // 配置参数
    const MAGNET_PREFIX = 'magnet:?xt=urn:btih:';
    const HASH_REGEX = /([0-9A-Za-z]{32,40})/g; // 匹配32-40位的哈希值
    const CONTAINER_SELECTOR = '.entry-content'; // 文章内容容器选择器

    // 创建磁力链接元素
    function createMagnetLink(hash) {
        const link = document.createElement('a');
        link.href = MAGNET_PREFIX + hash;
        link.textContent = hash;
        link.style.color = '#FF6600';
        link.style.margin = '0 4px';
        return link;
    }

    // 处理文本节点
    function processTextNode(node) {
        const text = node.nodeValue;
        const matches = [...text.matchAll(HASH_REGEX)];

        if (!matches.length) return;

        const fragment = document.createDocumentFragment();
        let lastIndex = 0;

        matches.forEach(match => {
            const hash = match[0];
            const index = match.index;

            // 添加前面的文本
            if (index > lastIndex) {
                fragment.appendChild(
                    document.createTextNode(text.substring(lastIndex, index))
                );
            }

            // 添加磁力链接
            fragment.appendChild(createMagnetLink(hash));
            lastIndex = index + hash.length;
        });

        // 添加剩余文本
        if (lastIndex < text.length) {
            fragment.appendChild(
                document.createTextNode(text.substring(lastIndex))
            );
        }

        // 替换原始节点
        node.parentNode.replaceChild(fragment, node);
    }

    // 主处理函数
    function processPage() {
        const container = document.querySelector(CONTAINER_SELECTOR);
        if (!container) return;

        // 遍历所有文本节点
        const walker = document.createTreeWalker(
            container,
            NodeFilter.SHOW_TEXT,
            {
                acceptNode: node =>
                    node.parentNode.tagName !== 'A' &&  // 跳过链接内的文本
                    HASH_REGEX.test(node.nodeValue) ?
                    NodeFilter.FILTER_ACCEPT :
                    NodeFilter.FILTER_SKIP
            }
        );

        const nodes = [];
        while (walker.nextNode()) nodes.push(walker.currentNode);
        nodes.forEach(processTextNode);
    }

    // 使用 MutationObserver 监听动态内容
    const observer = new MutationObserver(mutations => {
        mutations.forEach(mutation => {
            if (mutation.addedNodes.length) processPage();
        });
    });

    // 启动处理
    observer.observe(document.body, {
        childList: true,
        subtree: true,
        characterData: true
    });

    processPage(); // 初始处理
})();